package com.jiepos.mpos.biz.code.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.AppNoticeInfDao;
import com.jiepos.mpos.common.entity.App_Ins_InfEntity;
import com.jiepos.mpos.common.entity.App_Notice_InfEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;


/**
 *
 *
 * <p>标题: —— 客户端推送消息类</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @ProjectName:  [mpos]
 * @Package com.jiepos.mpos.biz.code.service
 * @author 余翼膑
 * @version 1.0
 * @since 2018年01月24号
 * @history（历次修订内容、修订人、修订时间等）
 */
@Service
public class NoticeInfService extends BaseService {

    @Autowired
    private AppNoticeInfDao appNoticeInfDao;


    /**
     * 通知公告（管理系统）
     * @param request
     * @param pagination
     * @param appNoticeInfEntity
     * @param appInsInfEntity
     * @return
     */
    public Map noticeInfListJson(HttpServletRequest request, Pagination pagination, App_Notice_InfEntity appNoticeInfEntity, App_Ins_InfEntity appInsInfEntity) {
        StringBuffer sb = getInitSql("t").append(",");
              sb.append("  T.NOTICE_UUID as UUID, T.NOTICE_TITLE, T.NOTICE_CONTENT,")
                .append(" T1.INS_CD||'-'||T1.INS_CN_NM AS INST_NAME,")
                .append(" T.publish_st||'-' || T2.CODE_DESC as PUBLISH_ST")
                .append(" FROM "+ DBConstant.Table.T_APP_NOTICE_INF+" T ")
                .append("  left join "+DBConstant.Table.T_APP_INS_INF+" t1 ")
                .append("  on t.ins_uuid = t1.ins_uuid")
                .append("  left join "+ DBConstant.Table.T_APP_CODE_LIST+" t2 ")
                .append("  ON T.publish_st = t2.code_val and t2.code_tp='PUBLISH_ST'");

        List list = new ArrayList();

        //标题
        if (!StringUtils.isBlank(appNoticeInfEntity.getNotice_title())) {
            sb.append(" AND T.notice_title LIKE ? ");
            list.add("%" + appNoticeInfEntity.getNotice_title() + "%");
        }
        //发布状态
        if (!StringUtils.isBlank(appNoticeInfEntity.getPublish_st())) {
            sb.append(" AND T.publish_st LIKE ? ");
            list.add("%" + appNoticeInfEntity.getPublish_st() + "%");
        }
        //机构名称
        if (!StringUtils.isBlank(appInsInfEntity.getIns_cn_nm())) {
            sb.append(" AND T1.ins_cn_nm LIKE ? ");
            list.add("%" + appInsInfEntity.getIns_cn_nm() + "%");
        }

        pagination.queryString = sb.toString();
        pagination = getInsAuthSql(request, pagination, "T", null);
        pagination = this.getOrderSql(pagination, "T");
        return appNoticeInfDao.getPaginationMap(pagination, "T", list);
    }

    /**
     * 详情页面
     * @param notice_uuid
     * @return
     */
    public Map getNoticeInfById(String notice_uuid) {
        if (StringUtils.isBlank(notice_uuid) || notice_uuid.equals("undefined")) {
            return new HashMap();
        }
        StringBuffer sb = getInitSql("t").append(",");
        sb.append("  T.NOTICE_UUID as uuid, t.notice_title, t.notice_content,")
                .append("T1.INS_CD||'-'||T1.INS_CN_NM AS INST_NAME,")
                .append(" T.publish_st||'-' || T2.CODE_DESC as PUBLISH_ST")
                .append(" FROM "+ DBConstant.Table.T_APP_NOTICE_INF+" T ")
                .append("  left join "+DBConstant.Table.T_APP_INS_INF+" t1 ")
                .append("  on t.ins_uuid = t1.ins_uuid")
                .append("  left join "+ DBConstant.Table.T_APP_CODE_LIST+" t2 ")
                .append("  ON T.publish_st = t2.code_val and t2.code_tp='PUBLISH_ST'")
                .append(" where notice_uuid = ? ");
        List<String> list = new ArrayList<>();
        list.add(notice_uuid);
        List<Map<String, Object>> results = appNoticeInfDao.queryForList(getOrderSql(sb.toString(), "t"), list);
        return results != null ? results.get(0) : new HashMap<String, Object>();

    }


    /**
     * 保存通知公告
     * @param appNoticeInfEntity
     * @param map
     */
    public void saveNoticeInf(App_Notice_InfEntity appNoticeInfEntity, Map map) {
        //当前用户
        appNoticeInfEntity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));

        if (org.apache.commons.lang.StringUtils.isBlank(appNoticeInfEntity.getIns_uuid())) {
            appNoticeInfEntity.setIns_uuid(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_INS_UUID)));
        }

        if (!StringUtils.isBlank(appNoticeInfEntity.getNotice_uuid())) {
            appNoticeInfEntity = (App_Notice_InfEntity) this.saveCommonData(appNoticeInfEntity, map, "update");
            List noChangeList = new ArrayList();
            noChangeList.add("notice_uuid");
            noChangeList.add("rec_crt_ts");
            appNoticeInfDao.update(appNoticeInfEntity, noChangeList);
        } else {
            appNoticeInfEntity.setNotice_uuid(IDFactoryUtil.getUUID());
            appNoticeInfEntity.setPublish_st(SystemConstant.PUBLISH_ST);// 已发布状态
            appNoticeInfEntity = (App_Notice_InfEntity) this.saveCommonData(appNoticeInfEntity, map, "null");
            appNoticeInfDao.save(appNoticeInfEntity);
        }

    }

    /**
     * 发布和取消发布
     * @param notice_uuids
     * @param publish_st
     * @param loginUser
     */
    public void updNoticeInfDetail(String notice_uuids, String publish_st, Map loginUser) {

        appNoticeInfDao.updateByIds("notice_uuid", notice_uuids, publish_st,
                String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
    }
    
    /**
     * 获取首页通知数据
     * @return
     */
    public List<Map<String, Object>> findListForHomePage(HttpServletRequest request){
    	/*获取登陆人所属机构级别*/
    	String insLevel = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_INS_LEVEL));
    	StringBuffer sql = new StringBuffer();
    	sql.append("SELECT * FROM (")
    	.append("SELECT NOTICE_UUID,")
    	.append("       NOTICE_TITLE,")
    	.append("       TO_CHAR(REC_CRT_TS, 'YYYY-MM-DD HH24:MI:SS') SEND_TIME")
    	.append("  FROM ").append(Table.T_APP_NOTICE_INF)
    	.append(" WHERE PUBLISH_ST = '").append(SystemConstant.PUBLISH_ST).append("'")
    	.append("   AND ").append(SystemConstant.REC_ST).append(" = '").append(SystemConstant.REC_ST_1).append("'");
    	Object[] params = null;
    	/*非顶级机构的登陆人，只能查询其所属O单机构的通知*/
    	if(!"1".equals(insLevel)){
    		sql.append("   AND INS_UUID =")
    		.append("       (SELECT II.INS_UUID")
    		.append("          FROM ").append(Table.T_APP_INS_INF).append(" II")
    		.append("         WHERE EXISTS")
    		.append("         (SELECT 1 FROM T_APP_INS_APP WHERE INS_UUID = II.INS_UUID)")
    		.append("           AND ROWNUM = 1")
    		.append("         START WITH II.INS_UUID = ?")
    		.append("        CONNECT BY PRIOR II.SUP_INS_UUID = II.INS_UUID)");
    		params = new Object[]{request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_INS_UUID)};
    	}
    	sql.append(" ORDER BY REC_CRT_TS DESC")
    	.append(") WHERE ROWNUM <= 10");
    	return appNoticeInfDao.queryForListMap(sql.toString(), params);
    }
    
    /**
     * 首页通知公告详情
     * @param uuid
     * @return
     */
    public Map<String, Object> findByUuidForHomePage(String uuid){
    	StringBuffer sql = new StringBuffer();
    	sql.append("SELECT * FROM (")
    	.append("SELECT NOTICE_UUID, NOTICE_TITLE, NOTICE_CONTENT, REC_UPD_USR_ID, TO_CHAR(REC_CRT_TS, 'YYYY-MM-DD HH24:MI:SS') SEND_TIME")
    	.append(" FROM ").append(Table.T_APP_NOTICE_INF)
    	.append(" WHERE PUBLISH_ST = '").append(SystemConstant.PUBLISH_ST).append("'")
    	.append(" AND ").append(SystemConstant.REC_ST).append(" = '").append(SystemConstant.REC_ST_1).append("'");
    	Object[] param = null;
    	if(StringUtils.isBlank(uuid)){
    		sql.append(" ORDER BY REC_CRT_TS DESC");
    		param = new Object[]{};
    	}else{
    		sql.append(" AND NOTICE_UUID = ? ");
    		param = new Object[]{uuid};
    	}
    	sql.append(") WHERE ROWNUM = 1");
    	List<Map<String, Object>> list = appNoticeInfDao.queryForListMap(sql.toString(), param);
    	return list == null || list.isEmpty() ? new HashMap<String, Object>() : list.get(0);
    }
}
